package com.hello.syn;

import java.util.ArrayList;
import java.util.List;

public class HappyCinema {

    public static void main(String[] args) {
        List<Integer> avaliable = new ArrayList<>();
        avaliable.add(1);
        avaliable.add(2);
        avaliable.add(3);
        avaliable.add(4);
        avaliable.add(5);
        avaliable.add(6);
        avaliable.add(7);

        List<Integer> seats1 = new ArrayList<>();
        seats1.add(1);
        seats1.add(2);
        seats1.add(3);

        List<Integer> seats2 = new ArrayList<>();
        seats2.add(6);
        seats2.add(7);

        Cinema cinema = new Cinema(avaliable,"happy sxt");
        new Thread(new Customer(cinema,seats1), "王小明").start();
        new Thread(new Customer(cinema,seats2), "王小花").start();
    }
}
// 顾客
class Customer implements Runnable {

    Cinema cinema;
    List<Integer> seats;

    public Customer(Cinema cinema, List<Integer> seats) {
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
       synchronized (cinema) {
           boolean flag = cinema.bookTickets(seats);
           if (flag) {
               System.out.println("出票成功"+Thread.currentThread().getName()+"->位置为："+seats);
           } else {
               System.out.println("出票失败"+Thread.currentThread().getName()+"->位置不够");
           }
       }
    }
}


// 影院
class Cinema {
    List<Integer> avaliable; // 座位
    String name; // 名称

    public Cinema(List<Integer> avaliable, String name) {
        this.avaliable = avaliable;
        this.name = name;
    }

    /**
     * 购票
     * @param seats
     * @return
     */
    public boolean bookTickets(List<Integer> seats) {
        System.out.println("可用位置："+avaliable);

        List<Integer> copy = new ArrayList<>();
        copy.addAll(avaliable);

        // 相减
        copy.removeAll(seats);

        // 判断大小
        if (avaliable.size() - copy.size() != seats.size()) {
            return false;
        }

        // 成功
        avaliable = copy;
        return true;
    }
}
